package com.mobilepay.moneypig.alipay;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.mobilepay.moneypig.model.activity.mine.VipActivity;
import com.mobilepay.moneypig.utils.ToastUtil;

import java.util.Map;

public class AlipayActivity extends FragmentActivity {

    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2016110102449736";
    /**
     * 商户私钥，pkcs8格式
     */
    public static final String RSA2_PRIVATE = "";
    public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANA1Bnar" +
            "734bV+ixXpoLaV1GJxcy6If1sct5uU+rb5fXMHWFugN9/oYxErToiQAtq" +
            "JcMMJGVfVXtHAOKJFlb4viC5/g+GFVqTl7ouikv26ARylj/KTXkHjvq0Y6" +
            "SqRSOqsw+J/HPr06cfrdeBKuV+m52PI6Mbyl2LZQlqp0ksVd/AgMBAAECg" +
            "YBN6HmJsF6GVp73cF9QzxJXF6gK8z61mUc1N1ATMrgoHhqA71AifGPgPL6" +
            "eOSECkxMxqhsGbuSeYYIJBQkC8vIjlBrr0pr6i/LU4xmRxxXqmHu9oArW5" +
            "y7uq3FoGdHXd8ZLVf4Ks+D8gOZ9HL1YW/B4WPpf8+3dh74MXXZ6qWQCGQJ" +
            "BAPs4bbAhQM6mjJw/3M/FbrvJmJhEO/RtaZEM63wFYj8TPWCel03ugc5oJj" +
            "H7xUqGsjffc56RQTGSj3TrnnJ9iMUCQQDUKxmg4g3tfqlYt9atXFY+paB4g" +
            "svg3mk+vYMJrLEtUpsrkMITJJAyQznLL4td06sbtWEughRYpzXNKcP6Ibtz" +
            "AkEApxKbGDS1RfnLr6plLqSuBSOIYVOXz/Hn8Dh4b62g7jPccOJn28NP/ra" +
            "TGFDJn8u+wJvR59XQVqiS0X5VjOzhxQJBAJO8FzJhdZVDtyOhjwhT3XHt3l" +
            "lLqi9Ab0RSraXU6+JFPOsO9zRhJ074ZIvI5WBF/UVj/PFnfkdk1x+uz1mil2" +
            "UCQCblYksF7rfk0mhNlGWK2CvVdTwCvRc9FrIgBYamcaXJOG/0PckJWqGHtk" +
            "TdrvNm7RxexlWPagO++mHBh2YfdgU=";

    private static final int SDK_PAY_FLAG = 1;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.showShortToast(AlipayActivity.this, "支付成功");
                        Intent intent = new Intent();
                        intent.setClass(AlipayActivity.this, VipActivity.class);
//                      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    } else if (TextUtils.equals(resultStatus, "4000")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.showShortToast(AlipayActivity.this, "支付失败");
                        finish();
                    } else if (TextUtils.equals(resultStatus, "5000")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.showShortToast(AlipayActivity.this, "重复请求");
                        finish();
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.showShortToast(AlipayActivity.this, "支付取消");
                        finish();
                    } else if (TextUtils.equals(resultStatus, "6002")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.showShortToast(AlipayActivity.this, "网络出错");
                        finish();
                    }
                    break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pay();
    }

    /**
     * 支付宝支付业务
     */
    public void pay() {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        String orderid = getIntent().getStringExtra("orderid");
        String price = getIntent().getStringExtra("price");
        String notify_url = getIntent().getStringExtra("notifyurl");
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, price, orderid, notify_url, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(AlipayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
